package com.generator.common.api;

import com.generator.common.api.build.BaseBuild;
import com.generator.common.constant.BaseConstant;
import com.generator.common.util.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.Properties;

/**
 * 业务模块的构建
 *
 * @author syl
 * @create 2018-03-24 01:10
 */
public class BiGenerator {
    private static final Logger LOG = Logger.getLogger(BiGenerator.class);

    public static final String DEFAULT_ENCODING = ConfigReadUtil.getYmlString("generate.encoding","UTF-8");

    /**
     * 生成方式 utf-8,不覆盖,默认存在即不生成
     * @param base BaseBuild
     */
    public BiGenerator(BaseBuild base){
        this(base, DEFAULT_ENCODING,true);
    }

    /**
     * 生成方式 utf-8
     * @param base BaseBuild
     * @param cover 是否覆盖  存在即不生成
     */
    public BiGenerator(BaseBuild base, boolean cover){
        this(base,DEFAULT_ENCODING,cover);
    }

    /**
     * 生成业务代码
     * @param base BaseBuild
     * @param encoding 编码
     * @param cover 是否覆盖  存在即不生成
     * @throws IOException
     * @throws TemplateException
     */
    public BiGenerator(BaseBuild base, String encoding, boolean cover){
        Configuration cfg = new Configuration(new Version(BaseConstant.FREEMARKER_VERSION));
        FileOutputStream fos = null;
        Writer out = null;
        try {
            String dir=System.getProperty("user.dir")+"/";
            LOG.info("System.getProperty(\"user.dir\"):"+System.getProperty("user.dir"));
            String fileName = base.getTemplateFileName();

            //src/main/resources/template/java/bean
            File directoryFile = inputToFile("/temp/"+base.getTemplateFileName());
            LOG.info("模板文件:"+directoryFile.getPath()+File.separator+fileName);

            cfg.setDirectoryForTemplateLoading(new File("t/temp"));
            Template template = cfg.getTemplate(fileName);


            File file = new File(base.getPath()+base.getFileName()+base.getFileType().getName());
            File temp = file.getParentFile();
            if(!temp.exists()){
                temp.mkdirs();
                temp.createNewFile();
            }
            if(file.exists() && !cover)return;


            LOG.info("文件输出路径："+file.getPath());
            fos = new FileOutputStream(file);
            out = new OutputStreamWriter(fos, StringUtils.isEmpty(encoding) ? DEFAULT_ENCODING : encoding);
            template.process(base, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out != null)out.close();
                if(fos != null)fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将InputStream写入本地文件
     * @param destination 写入本地目录
     * @param input 输入流
     * @throws IOException IOException
     */
    public static File inputToFile(String path)
            throws IOException {
        InputStream in = BiGenerator.class.getResourceAsStream(path);
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
        File targetFile = new File("t/"+path);
        if(!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
        }

        OutputStream outStream = new FileOutputStream(targetFile);
        outStream.write(buffer);
        return targetFile;
    }

    public boolean exists() throws IOException {
        String root = BiGenerator.class.getResource("/").getPath();
        File f = new File(root + "library/a.txt");
        return f.exists();
    }

}
